<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/12
 * Time: 16:54
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\lib;

class Menu
{
    /**
     * 返回菜单
     * @param int $pid
     * @param array $menuList
     * @param string $type
     * @return array
     */
    public static function buildMenuChild(int $pid = 0, array $menuList = [], string $type = 'child'): array
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = self::buildMenuChild($v['id'], $menuList, $type);
                if (!empty($child)) {
                    $node[$type] = $child;
                }
                if (!empty($node['controller']) && !empty($node['action'])) {
                    if ($node['type'] == 0) {
                        $node['href'] = (string)url("/admin/" . $node['controller'] . "/" . $node['action']);
                    } else if ($node['type'] == 1) {
                        $node['href'] = (string)url("/index/" . $node['controller'] . "/" . $node['action']);
                    }
                } else {
                    $node['href'] = "";
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }

    /**
     * @param $arr
     * @param int $pid
     * @return array
     */
    public static function MenuTree($arr, $pid = 0)
    {
        $list = array();
        foreach ($arr as $key => $v) {
            if ($v['parent_id'] == $pid) {
                $tmp = self::arrayMenu($arr, $v['id']);
                if ($tmp) {
                    $v['list'] = $tmp;
                }
                $list[] = $v;
            }
        }
        return $list;
    }

    /**
     * @param $arr
     * @param int $pid
     * @return array
     */
    public static function arrayMenu($arr, $pid = 0)
    {
        $list = array();
        foreach ($arr as $key => $v) {
            if ($v['parent_id'] == $pid) {
                $tmp = self::arrayMenu($arr, $v['id']);
                if ($tmp) {
                    $v['list'] = $tmp;
                }
                $list[] = $v;
            }
        }
        return $list;
    }
}
